package saei.servlet;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import saei.bean.Usuario;

public class ServletBase extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static ThreadLocal<Usuario> loggedUser = new ThreadLocal<Usuario>();
	private static int serverPort;
	protected String mensajeError;
	protected String mensajeExito;
	protected String urlOk;
	protected String urlError;
	
    public ServletBase(String urlOk, String urlError) {
        super();
        this.urlOk = urlOk;
        this.urlError = urlError;
    }
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		mensajeError = null;
		mensajeExito = null;
		
		request.getSession().removeAttribute("values");
		
		redirect(request, response);
	}
    
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		redirect(request, response);
	}

    protected void redirect(HttpServletRequest request, HttpServletResponse response) 
			throws ServletException, IOException {
    	redirect(request, response, mensajeError != null);
    }
    
	@SuppressWarnings("unchecked")
	protected void redirect(HttpServletRequest request, HttpServletResponse response, boolean mantenerParametros) 
			throws ServletException, IOException {
		RequestDispatcher dispatcher = null;
		
		if(mensajeError != null) {
			request.getSession().removeAttribute("mensajeExito");
			request.getSession().setAttribute("mensajeError", mensajeError);
			dispatcher = request.getRequestDispatcher(urlError);
		} else {
			request.getSession().removeAttribute("mensajeError");
			request.getSession().setAttribute("mensajeExito", mensajeExito);
			dispatcher = request.getRequestDispatcher(urlOk);
		}
		
		if (mantenerParametros) {
			HashMap<String, String> values = new HashMap<String, String>(); 
			Enumeration<String> paramNames = request.getParameterNames();
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				values.put(paramName, request.getParameter(paramName));
			}
			request.getSession().setAttribute("values",values);
		} else {
			request.getSession().removeAttribute("values");
		}
		
		dispatcher.forward(request, response);
	}

	public static Usuario getLoggedUser() {
		return loggedUser.get();
	}

	public static void setLoggedUser(Usuario usuario) {
		ServletBase.loggedUser.set(usuario);
	}

	public static int getServerPort() {
		return serverPort;
	}

	public static void setServerPort(int serverPort) {
		ServletBase.serverPort = serverPort;
	}
}
